package pl.smath.expression.model;

import pl.smath.expression.utils.SortProductComparator;

public class DivisionTerm extends AbstractMultiTerm {

	public DivisionTerm() {
		super(":");
	}

	/**
	 * Porówanie wyrazen
	 */
	public boolean isAbsTheSame(Term term){
		
		if(!(term instanceof DivisionTerm))
			return false;
		
		return super.isAbsTheSame(term);
	}


	/**
	 * Try to evaluate expression
	 */
	public Term evaluate(){

		float value = 1;

		for(Term term : getTerms()){
		
			Term eval = term.evaluate();
			if(eval instanceof NumberTerm){
				value /= ((NumberTerm)eval).getValue();
			}
			else{
				return this;
			}
		}
		
		if(isNegative()){
			value = -value;
		}
		
		return new NumberTerm(value);
	}
	
	/**
	 * Uporzadkowanie minusow
	 */
	@Override
	public void normalizeSign(){
	
		boolean negative = false;
		for(Term term : getTerms()){
			if(term.isNegative()){
				negative = !negative;
				term.setNegative(false);
			}
		}
		
		setNegative(isNegative() != negative);

	}
	
	/**
	 * Proste sortowanie. Może wystarczy?
	 */
	@Override
	public void sort() {
		sortTerms(new SortProductComparator());
	}

	/**
	 * Zamiana do stringa
	 */
	public String toString(){
		String output = "";
		
		for(Term term : getTerms()){
			
			if(output.length() > 0){
				output += ":";
			}

			if(term instanceof SumTerm)
				output += "(" + term.toString() + ")";
			else
				output += term.toString();
		}
		
		if(isNegative())
			output = "-" + output;
		
		return output;
	}

	@Override
	protected AbstractMultiTerm createObject() {
		// TODO Auto-generated method stub
		return null;
	}

}
